package com.wjx.dingcan.filter;

import java.io.BufferedReader;  
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;
import java.io.IOException;  
import java.io.InputStream;
import java.io.InputStreamReader;  
import java.nio.charset.Charset;  
  



import javax.servlet.ServletInputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletRequestWrapper;  
  



import org.apache.commons.lang.StringUtils;  

import com.sun.xml.messaging.saaj.util.ByteInputStream;
  
public class MAPIHttpServletRequestWrapper extends HttpServletRequestWrapper {  
    private final byte[] body;   
    
      
    public MAPIHttpServletRequestWrapper(HttpServletRequest request)  
            throws IOException {    
        super(request);    
        body = readBytes(request.getInputStream());  
    }    
    
    @Override    
    public BufferedReader getReader() throws IOException {    
        return new BufferedReader(new InputStreamReader(getInputStream()));    
    }    
    
    @Override    
    public ServletInputStream getInputStream() throws IOException {    
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);    
        return new ServletInputStream() {    
        	
            @Override
			public int readLine(byte[] b, int off, int len) throws IOException {
				return super.readLine(b, off, len);
			}

			@Override    
            public int read() throws IOException {    
                return bais.read();    
            }

			@Override
			public int read(byte[] b) throws IOException {
				return bais.read(b);
			}

			@Override
			public int read(byte[] b, int off, int len) throws IOException {
				return bais.read(b, off, len);
			}

			@Override
			public long skip(long n) throws IOException {
				return bais.skip(n);
			}

			@Override
			public int available() throws IOException {
				return bais.available();
			}

			@Override
			public void close() throws IOException {
				bais.close();
			}

			@Override
			public synchronized void mark(int readlimit) {
				bais.mark(readlimit);
			}

			@Override
			public synchronized void reset() throws IOException {
				bais.reset();
			}

			@Override
			public boolean markSupported() {
				return bais.markSupported();
			}
            
			
            
            
        };    
    }   
      
    /** 
     * 通过BufferedReader和字符编码集转换成byte数组 
     * @param br 
     * @param encoding 
     * @return 
     * @throws IOException  
     */  
    private byte[] readBytes(InputStream is) throws IOException{  
        int len ;
        byte[] buf = new byte[1024];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while((len = is.read(buf)) > 0) {
        	outputStream.write(buf, 0, len);
        	
        }
        return outputStream.toByteArray();  
    }  
      
}
